<script setup lang="ts">
import { ref } from 'vue';
import { useRole, useDelRole } from '@/api/systemRole';
import { handleMessage } from '@/utils/globalEvent';
import type { IRoleInfo } from '@/api/systemRole/type';

const emits = defineEmits(['handleAddUser', 'handleEditUser', 'handleDuty']);
// loading
const loading = ref(true);
// 角色列表
const roleList = ref<IRoleInfo[]>([]);
// 当前选中角色
const activeId = ref<number | null>(null);

// 获取角色
const getRole = async () => {
	if (!loading.value) loading.value = true;
	try {
		const data = await useRole();
		activeId.value = data?.[0]?.id;
		roleList.value = data;
		emits('handleDuty', activeId.value);
	} catch (error) {
		throw new Error('获取角色未知异常,请联系开发人员');
	} finally {
		loading.value = false;
	}
};
getRole();

// 当前移入角色
const hoverRoleId = ref<number | null>(null);
// 移入角色列表
const onMouseover = (e: Event) => {
	const dom: HTMLElement = e.target as HTMLElement;
	if (dom?.children?.length > 1) return;
	const id = Number(dom.dataset.id);
	if (!id || id === hoverRoleId.value) return;
	hoverRoleId.value = id;
};
// 移出角色列表
const onMouseleave = () => {
	hoverRoleId.value = null;
};

// 点击角色
const clickRoleList = (e: Event) => {
	const dom: HTMLElement = e.target as HTMLElement;
	if (dom?.children?.length > 1) return;
	const id = Number(dom.dataset.id);
	if (activeId.value === id) return;
	activeId.value = id;
	emits('handleDuty', id);
};
// 新增角色
const clickAddUser = () => {
	emits('handleAddUser');
};
// 编辑角色
const clickEdit = (id: number, role: string) => {
	emits('handleEditUser', { id, role });
};
// 删除角色
const clickDel = async (id: number) => {
	loading.value = true;
	try {
		const result = await useDelRole({ id });
		if (!result) return;
		handleMessage(result);
	} catch (error) {
		throw new Error('删除角色未知异常,请联系开发人员');
	} finally {
		getRole();
	}
};

defineExpose({
	getRole,
});
</script>

<template>
	<div v-part-loading="loading" class="role">
		<div class="role-list">
			<ul class="role-ul" @click="clickRoleList" @mouseover="onMouseover" @mouseleave="onMouseleave">
				<template v-for="item in roleList" :key="item.id">
					<div class="role-item">
						<li class="role-li" :class="activeId === item.id && 'active'" :data-id="item.id">
							{{ item.role }}
						</li>
						<div v-if="item.edit && hoverRoleId === item.id" class="role-operate">
							<span class="role-edit" @click="clickEdit(item.id, item.role)">编辑</span>
							<span class="role-del" @click="clickDel(item.id)">删除</span>
						</div>
					</div>
				</template>
			</ul>
		</div>
		<el-button @click="clickAddUser">新增</el-button>
	</div>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
